package com.vidmt.api.modules.sys.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Userinfos;
import com.taobao.api.request.OpenimUsersAddRequest;
import com.taobao.api.request.OpenimUsersDeleteRequest;
import com.taobao.api.request.OpenimUsersGetRequest;
import com.taobao.api.request.OpenimUsersUpdateRequest;
import com.taobao.api.response.OpenimUsersAddResponse;
import com.taobao.api.response.OpenimUsersDeleteResponse;
import com.taobao.api.response.OpenimUsersGetResponse;
import com.taobao.api.response.OpenimUsersUpdateResponse;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.service.BaseService;
import com.vidmt.api.common.exceptions.UserExistsException;
import com.vidmt.api.common.exceptions.UserNotExistsException;
import com.vidmt.api.common.utils.StrUtil;
import com.vidmt.api.modules.sys.Enums.LvlType;
import com.vidmt.api.modules.sys.Enums.UserStatus;
import com.vidmt.api.modules.sys.entity.User;
import com.vidmt.api.modules.sys.utils.PropUtil;

@Service
public class ImService extends BaseService {
	private static final Logger log = LoggerFactory.getLogger(ImService.class);
	private static final String SERVER_URL = "http://gw.api.taobao.com/router/rest";
	private static final String IM_KEY = Global.getConfig("ali.im.key");
	private static final String IM_SECRET = Global.getConfig("ali.im.secret");
	private static final TaobaoClient client = new DefaultTaobaoClient(SERVER_URL, IM_KEY, IM_SECRET);

	public static void main(String[] args) throws UserNotExistsException {
		Long uid = 100002L;
		ImService imsvc = new ImService();
		Map map = imsvc.isOnline(uid);
		System.out.println(map);
		imsvc.deleteUser(uid);
		Map map2 = imsvc.isOnline(uid);
		System.out.println(map2);
	}

	public void addUser(User[] users, String[] pwds) throws UserExistsException {
		List<Userinfos> list = new ArrayList<Userinfos>();
		for (int i = 0; i < users.length; i++) {
			User user = users[i];
			Userinfos person = toAliUser(user);
			person.setPassword(pwds[i]);
			list.add(person);
		}
		OpenimUsersAddRequest req = new OpenimUsersAddRequest();
		req.setUserinfos(list);
		OpenimUsersAddResponse rsp;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			log.error("淘宝添加好友出错:", e);
			throw new IllegalStateException(e);
		}
		if (rsp.getErrorCode() != null) {
			if ("isv.data-duplicate-error".equals(rsp.getBody())) {
				log.error("淘宝用户已存在:{}", rsp.getBody());
				throw new UserExistsException();
			} else {
				log.error("淘宝添加用户出错:{}", rsp.getBody());
				throw new IllegalStateException("淘宝添加用户出错");
			}
		}
	}

	public Map<Long, Boolean> isOnline(Long... uids) throws UserNotExistsException {
		String uidstr = StrUtil.join(uids);
		OpenimUsersGetRequest req = new OpenimUsersGetRequest();
		req.setUserids(uidstr);
		try {
			OpenimUsersGetResponse rsp = client.execute(req);
			List<Userinfos> uinfos = rsp.getUserinfos();
			if (rsp.getErrorCode() != null) {
				log.error("淘宝获取上线状态出错:{}", rsp.getBody());
				throw new IllegalStateException("淘宝获取上线状态出错");
			}
			if (uinfos == null) {
				throw new UserNotExistsException("uids not exist:" + Arrays.toString(uids));
			}
			Map<Long, Boolean> map = new HashMap<>(uinfos.size());
			for (Userinfos uinfo : uinfos) {
				Long uid = Long.valueOf(uinfo.getUserid());
				boolean online = uinfo.getStatus() == 1;
				map.put(uid, online);
			}
			return map;
		} catch (ApiException e) {
			log.error("淘宝获取上线状态出错:", e);
			throw new IllegalStateException(e);
		}
	}

	public List<User> findAliUsers(Long... uids) throws UserNotExistsException {
		String uidstr = StrUtil.join(uids);
		OpenimUsersGetRequest req = new OpenimUsersGetRequest();
		req.setUserids(uidstr);
		try {
			OpenimUsersGetResponse rsp = client.execute(req);
			if (rsp.getErrorCode() != null) {
				log.error("淘宝获取上线状态出错:{}", rsp.getBody());
				throw new IllegalStateException("淘宝获取上线状态出错");
			}
			List<Userinfos> uinfos = rsp.getUserinfos();
			if (uinfos == null) {
				throw new UserNotExistsException("uids not exist:" + Arrays.toString(uids));
			}
			List<User> list = Lists.newArrayList();
			for (Userinfos uinfo : uinfos) {
				User user = fromAliUser(uinfo);
				list.add(user);
			}
			return list;
		} catch (ApiException e) {
			log.error("淘宝获取上线状态出错:", e);
			throw new IllegalStateException(e);
		}
	}

	public void updateUser(User... users) {
		List<Userinfos> list = new ArrayList<Userinfos>();
		for (int i = 0; i < users.length; i++) {
			User user = users[i];
			Userinfos person = toAliUser(user);
			list.add(person);
		}
		OpenimUsersUpdateRequest req = new OpenimUsersUpdateRequest();
		req.setUserinfos(list);
		try {
			OpenimUsersUpdateResponse rsp = client.execute(req);
			if (rsp.getErrorCode() != null) {
				log.error("淘宝更新用户出错:{}", rsp.getBody());
				throw new IllegalStateException("淘宝更新用户出错");
			}
		} catch (ApiException e) {
			log.error("淘宝更新用户出错:", e);
			throw new IllegalStateException(e);
		}

	}

	public void changePassword(Long uid, String pwd) {
		List<Userinfos> list = new ArrayList<Userinfos>();
		for (int i = 1; i < 10; i++) {
			Userinfos person = new Userinfos();
			person.setUserid(uid + "");
			person.setPassword(pwd);
			list.add(person);
		}
		OpenimUsersUpdateRequest req = new OpenimUsersUpdateRequest();
		req.setUserinfos(list);
		try {
			OpenimUsersUpdateResponse rsp = client.execute(req);
			if (rsp.getErrorCode() != null) {
				log.error("淘宝更新密码出错:{}", rsp.getBody());
				throw new IllegalStateException("淘宝更新密码出错");
			}
		} catch (ApiException e) {
			log.error("淘宝更新密码出错:", e);
			throw new IllegalStateException(e);
		}

	}

	public void deleteUser(Long... uids) {
		String uidstr = StrUtil.join(uids);
		OpenimUsersDeleteRequest req = new OpenimUsersDeleteRequest();
		req.setUserids(uidstr);
		try {
			OpenimUsersDeleteResponse rsp = client.execute(req);
			if (rsp.getErrorCode() != null) {
				log.error("淘宝删除用户出错:{}", rsp.getBody());
				throw new IllegalStateException("淘宝删除用户出错");
			}
		} catch (ApiException e) {
			log.error("淘宝删除用户出错:", e);
			throw new IllegalStateException(e);
		}

	}

	private static User fromAliUser(Userinfos info) {
		User user = new User();
		user.setId(Long.valueOf(info.getUserid()));
		user.setName(info.getName());
		user.setNick(info.getNick());
		// user.setAvatarUri(avatarUri);
		user.setEmail(info.getEmail());
		user.setPhone(info.getMobile());
		user.setAddress(info.getAddress());
		user.setSignature(info.getRemark());
		user.setSex("M".equals(info.getGender()) ? User.SEX_M : User.SEX_F);
		user.setOnline(info.getStatus() == 1);
		String extra = info.getExtra();
		if (extra != null) {
			JSONObject json = JSON.parseObject(extra);
			user.setAvoidDisturb(json.getBoolean("avoidDisturb"));
			user.setLocPrivate(json.getBoolean("locPrivate"));
			user.setBirth(new java.sql.Date(json.getDate("birth").getTime()));

			String lvlStr = json.getString("lvl");
			if (lvlStr != null) {
				user.setLvl(LvlType.valueOf(lvlStr));
			}

			String statusStr = json.getString("status");
			user.setStatus(UserStatus.valueOf(statusStr));
			user.setPhotoUri(json.getString("photoUri"));
		}
		return user;
	}

	private static Userinfos toAliUser(User user) {
		Userinfos person = new Userinfos();
		person.setUserid(user.getId() + "");
		// person.setPassword(pwd);
		person.setName(user.getName());
		person.setNick(user.getNick());
		person.setIconUrl(PropUtil.get(PropUtil.KEY_SYS_USER_FILE_URL_PREFIX) + user.getAvatarUri());
		person.setEmail(user.getEmail());
		person.setMobile(user.getPhone());
		person.setAddress(user.getAddress());
		person.setRemark(user.getSignature());
		person.setGender(user.getSex() == User.SEX_M ? "M" : "F");

		JSONObject extrajson = new JSONObject();
		extrajson.put("avoidDisturb", user.getAvoidDisturb());
		extrajson.put("locPrivate", user.getLocPrivate());
		extrajson.put("birth", user.getBirth());
		extrajson.put("lvl", user.getLvl());
		extrajson.put("lvlttl", user.getLvlttl());
		extrajson.put("status", user.getStatus());
		extrajson.put("photoUri", user.getPhotoUri());

		person.setExtra(extrajson.toJSONString());
		// person.setAge(age);
		// obj3.setTaobaoid("tbnick123");
		// person.setCareer("career" + i);
		// obj3.setVip("demo");
		// person.setWechat("wechat" + i);
		// person.setQq("qq" + i);
		// person.setWeibo("webo" + i);
		return person;
	}
}
